//
//  PxRequestHelper.m
//  PxHelper
//
//  Created by lpc on 2019/10/18.
//  Copyright © 2019 lpc. All rights reserved.
//

#import "PxRequestHelper.h"

@implementation PxRequestHelper

+ (NSDictionary *)commonHeaders {
    NSMutableDictionary *header = [NSMutableDictionary dictionary];
    [header setValue:@"application/json" forKey:@"Accept"];
    [header setValue:@"application/json" forKey:@"Content-type"];
    [header setValue:@"1.0" forKey:@"version"];
    return [header copy];
}

+ (NSURLSessionTask *)startRequest:(NSURLRequest *)request
                           headers:(NSDictionary *)headers
                        completion:(PxHttpResponseBlock)completion
{
    NSMutableURLRequest *req = [request mutableCopy];
    for (NSString *h in headers) {
        [req setValue:headers[h] forHTTPHeaderField:h];
    }

    NSURLSession *session = session = [NSURLSession sharedSession];
    NSURLSessionTask *task = [session dataTaskWithRequest:req completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
#ifdef DEBUG
        NSLog(@"\nRequest:%@\nResponse:%@:", req.URL.absoluteString, str);
#endif
        dispatch_async(dispatch_get_main_queue(), ^{
            completion(data, response, error);
        });
    }];
    [task resume];

    return task;
}

+ (void)postToUrl:(NSURL *)url
           params:(NSDictionary *)params
       completion:(PxHttpResponseBlock)completion {

    NSMutableString *paramStr = [NSMutableString new];
    for (NSString *key in params){
        NSString *val = params[key];
        [paramStr appendFormat:@"%@=%@&", key, val];
    }
    if (paramStr.length > 0) {
        [paramStr deleteCharactersInRange:NSMakeRange(paramStr.length-1, 1)];
    }

    NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30];
    req.HTTPMethod = @"POST";
    req.HTTPBody = [paramStr dataUsingEncoding:NSUTF8StringEncoding];

    NSDictionary *headers = [self commonHeaders];
    [self startRequest:req headers:headers completion:completion];
}

+ (void)getWithUrl:(NSURL *)url
            params:(NSDictionary *)params
        completion:(PxHttpResponseBlock)completion
{
    __block NSString *urlStr = url.absoluteString;
    if (params.count > 0) {
        urlStr = [urlStr stringByAppendingString:@"?"];
        [params enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, NSString *  _Nonnull obj, BOOL * _Nonnull stop) {
            urlStr = [urlStr stringByAppendingFormat:@"&%@=%@", key, obj];
        }];
        url = [NSURL URLWithString:urlStr];
    }
    NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30];
    req.HTTPMethod = @"GET";

    NSDictionary *headers = [self commonHeaders];
    [self startRequest:req headers:headers completion:completion];
}

@end
